package com.ymx.darling.bean.entity.fill;

import com.ymx.darling.bean.entity.BeanInfo;
import com.ymx.darling.bean.entity.FieldInfo;
import com.ymx.darling.exception.EntityException;
import com.ymx.darling.util.ReflectUtil;

/**
 * 实体填充包装器
 * @author 爱Java的小于
 */
public class FillEntity {
    private final Object entity;
    private final BeanInfo beanInfo;

    public FillEntity(Object entity, BeanInfo beanInfo) {
        this.entity = entity;
        this.beanInfo = beanInfo;
    }

    /**
     * 获取实体对象
     * @return 实体对象
     */
    public Object getEntity() {
        return entity;
    }

    /**
     * 为指定字段赋值
     * @param fieldName 字段名
     * @param value 字段值
     */
    public void setValue(String fieldName, Object value) {
        FieldInfo fieldInfo = this.getFieldInfo(fieldName);
        ReflectUtil.setValue(fieldInfo.getField(), entity, value);
    }

    private FieldInfo getFieldInfo(String fieldName) {
        FieldInfo fieldInfo = beanInfo.getFieldMap().get(fieldName);
        if (fieldInfo == null) {
            throw new EntityException(String.format("类'%s'中找不到字段'%s'", entity.getClass().getName(), fieldName));
        }
        return fieldInfo;
    }

    /**
     * 获取字段值
     * @param fieldName 字段名
     * @return 字段值
     */
    public Object getValue(String fieldName) {
        FieldInfo fieldInfo = this.getFieldInfo(fieldName);
        return ReflectUtil.getValue(fieldInfo.getField(), entity);
    }
}
